首页 > 试题广场 >

求两个多项式的和

[编程题]求两个多项式的和
  • 热度指数:4814 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
输入两个多项式,计算它们的和。 每个多项式有若干对整数表示,每组整数中,第一个整数表示系数(非0),第二个整数表示该项的次数。 如由3 3 5 -2 1 4 0表示3x^5 - 2 * x + 4其中第一个3表示该多项式由三个整数对表示。

输入描述:
输入为两行,分别表示两个多项式。表示每项的整数对按照次数大小降序给出。(次数绝对值小于1000,系数绝对值小于10000)


输出描述:
按照降次顺序输出表示和多项式的整数对(系数为0的整数对不用输出,整数对由空格分隔,最后一个整数对后不添加空格)
示例1

输入

3 3 5 -2 1 4 0
4 2 3 -1 2 1 1 3 0

输出

3 5 2 3 -1 2 -1 1 7 0
import sys

result = []
aa = []
for line in sys.stdin:
    dd = list(map(int, line[:-1].split()))[1:]
    aa.append(dd)

rr = sorted(aa[0][1::2] + aa[1][1::2], reverse=True)
max_exp = rr[0]
min_exp = rr[-1]

for i in range(min_exp, max_exp + 1):
    result.append([0, i])

locations = {}
for location, (conf, exp) in enumerate(result):
    # print(exp, location)
    locations[exp] = location

aa_cc = [(i, j) for i,j in zip(aa[0][0::2], aa[0][1::2])]
bb_cc = [(i, j) for i,j in zip(aa[1][0::2], aa[1][1::2])]
# print(max_exp)
for conf, exp in aa_cc + bb_cc:
    result[locations[exp]][0] += conf

resultss = ""
for conf, exp in result[::-1]:
    if conf != 0:
        # print(conf, exp)
        resultss += str(conf) + " " + str(exp) + " "
print(resultss[:-1])

发表于 2024-03-16 01:05:41 回复(0)